package com.xlblog.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.xlblog.blog.entity.TBlog;
import com.xlblog.blog.form.BlogForm;
import com.xlblog.blog.mapper.TBlogMapper;
import com.xlblog.blog.service.TBlogService;
import com.xlblog.blog.service.TCountService;
import com.xlblog.blog.utils.FileUtil;
import com.xlblog.blog.utils.RespBean;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;


/**
 * <p>
 *  前端控制器
 * </p>
 */
@RestController
@RequestMapping("/blog")
@CrossOrigin
public class TBlogController {

    @Autowired
    TBlogService tBlogService;
    @Autowired
    TCountService TCountService;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    RespBean respBean = RespBean.build();

    /**
     * 分页查询
     * @param current
     * @param size
     * @param published
     * @param flag
     * @param share_statement
     * @param is_delete
     * @return
     */
    @CrossOrigin(origins = "*",maxAge = 3600)
    @GetMapping("/getByPage")
    @ApiOperation("博客分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current",value = "当前页") ,
            @ApiImplicitParam(name = "size",value = "每页的数量"),
            @ApiImplicitParam(name = "published",value = "是否公开"),
            @ApiImplicitParam(name = "flag",value = "原创或转载"),
            @ApiImplicitParam(name = "share_statement",value = "草稿"),
            @ApiImplicitParam(name = "is_delete",value = "是否已删除"),
    })
    public RespBean getByPage(Long current, Long size, Boolean published,
                              String flag, Boolean share_statement, Boolean is_delete,HttpServletResponse resp){
        resp.setHeader("Access-Control-Allow-Origin","*");
        return tBlogService.pageBlogs(current, size,published,flag,share_statement,is_delete);
    }

    /**
     * 前台分页
     * @param current
     * @param size
     * @param type_id
     * @param tags_id
     * @return
     */
    @GetMapping("/vuefindByPage")
    public RespBean vuefindByPage(Long current, Long size, Long type_id, Long tags_id,String source,HttpServletResponse resp){
        resp.setHeader("Access-Control-Allow-Origin","*");
        return tBlogService.vuefindByPage(current, size,type_id,tags_id,source);
    }

    @GetMapping("/vuefindHotBlog")
    public RespBean vuefindHotBlog(){
        return tBlogService.vuefindHotBlog();
    }

    /**
     * 根据博客标题查询
     * @param title
     * @return
     */
    @GetMapping("/getByTitle")
    @ApiOperation("通过文章标题查询")
    @ApiImplicitParam(name = "title",value = "文章的标题")
    public RespBean findByTitle(String title){
        return tBlogService.getByTitle(title);
    }

    /**
     * 保存文章和标签
     * @param params
     * @return
     */
    @PostMapping("/savaBT")
    public RespBean getByBlogIdBlogTag(@RequestBody HashMap<String,Object> params) {
        RespBean check = BlogForm.check(params);
        if (check.getStatus() == 500) {
            return check;
        }else {
            return tBlogService.saveBT(params);
        }
    }

    /**
     * 暂时保存博客
     * @param params
     * @return
     */
    @PostMapping("/temporarySave")
    public RespBean temporarySave(@RequestBody HashMap<String,Object> params){
        RespBean checkTemporaryBlog = BlogForm.checkTemporaryBlog(params);
        if (checkTemporaryBlog.getStatus() == 500) {
            return checkTemporaryBlog;
        }
        else {
            return tBlogService.temporarySave(params);
        }
    }

    /**
     * 更新博客和标签
     * @param params
     * @return
     */
    @PutMapping("/updateBlog")
    public RespBean updateBlog(@RequestBody HashMap<String,Object> params){
        RespBean checkUpdateBlog = BlogForm.check(params);
        if (checkUpdateBlog.getStatus() == 500) {
            return checkUpdateBlog;
        }
        else {
            return tBlogService.updateBlog(params);
        }
    }

    /**
     * 逻辑删除
     * @param id
     * @return
     */
    @DeleteMapping("/logicDeleteBlog")
    public RespBean logicDeleteBlog(String id){
        TBlog tBlog = tBlogService.getById(id);
        if (tBlog != null){
            return tBlogService.logicDeleteBlog(id);
        }else {
            respBean.setStatus(500);
            respBean.setMsg("没有数据");
            return respBean;
        }
    }

    /**
     * 删除博客和对应标签
     * @param id
     * @return
     */
    @DeleteMapping("/deleteBlog")
    public RespBean deleteBlog(String id){
        TBlog tBlog = tBlogService.getById(id);
        if (tBlog != null){
            return tBlogService.deleteBT(id);
        }else {
            respBean.setStatus(500);
            respBean.setMsg("没有数据");
            return respBean;
        }
    }

    /**
     * 还原删除的博客
     * @param id
     * @return
     */
    @GetMapping("/recoveryBlog")
    public RespBean recoveryBlog(String id){
        return tBlogService.recoveryBlog(id);
    }

    /**
     * 根据id查找博客
     * @param id
     * @return
     */
    @GetMapping("/getByBlogId")
    public RespBean getByBlogId(String id){
        return tBlogService.getByBlogId(id);
    }

    /**
     * 统计数据countBlog
     * @return
     */
//    @GetMapping("/countBlog")
//    public RespBean countBlog(){
//        return tBlogService.countBlog();
//    }


    /**
    * 获取访问量
    */
//    @CrossOrigin(origins = "*",maxAge = 3600)
    @GetMapping("/getViewCount")
    public long countBlog() {
//    public Integer countBlog(HttpServletRequest request) {

//        ServletContext context = request.getServletContext();
//        //从ServletContext中获取计数器对象
//        Integer count = (Integer) context.getAttribute("counter");
//        // 如果为空，则在ServletContext中设置一个计数器的属性
//        if (count == null) {
//            count = 1;
//            context.setAttribute("counter", count);
//        } else {
//            context.setAttribute("counter", count + 1);
//        }
//        System.out.println("访问次数 " + count);
        //存入数据库

        //return count;
//        return tBlogService.countBlog(params);
        return TCountService.countBlog();
    }

    /**
    * 获取评论总数
    */
//    @GetMapping("/getCommentCount")
//    public int getCommentCount(){
//        return tBlogService.getCommentCount();
//    }

    /**
    * 富文本
    * */
    //上传目录绝对路径
    @Value("${file.upload.abpath}")
    private String abpath;

    //上传目录url
    @Value("${file.upload.mdImageDir}")
    private String mdImageDir;

    //端口号
    @Value("${server.port}")
    private String port;


//    //上传md文件
//    @PostMapping("/saveMd")
//    //注意参数传递是以json格式，因此用@RequestBody定义接收参数
//    public String saveMd(@RequestBody JSONObject param){
//        System.out.println("param:");
//        System.out.println(param);
//        //取出java中对应参数的值
//        String str = param.getString("content");
//        String name=param.getString("name");
//        String typeId=param.getString("typeId");
//        //文件保存路径  F:\note\555.md
//        String filepath=abpath+name+".md";
//        System.out.println(filepath);
//        FileUtil.string2File(str,filepath);
//        return "ok";
//    }
//
//    //上传图片
//    @PostMapping("/uploadFile")
//    public String uploadFile(@RequestParam("image") MultipartFile file, HttpServletRequest request){
//        //上传的绝对路径  F:/note/assets/
//        String imgAbPath=abpath+"assets/";
//        System.out.println(imgAbPath);
//        //绝对路径对应urlpath   http://localhost:4000/note/assets/
//        String imgUrlDir="http:"+request.getHeader("Origin").split(":")[1]+":"+port+mdImageDir;
//        System.out.println(imgUrlDir);
//        //返回对应的File类型f
//        File f = FileUtil.upload(file, imgAbPath);
//
//        //返回图片地址 http://localhost:4000/note/assets/image-20200924014614792.png  注意图片名子中间有加密
//        return imgUrlDir+f.getName();
//
//    }


//上传md文件
@PostMapping("/saveMd")
    //注意参数传递是以json格式，因此用@RequestBody定义接收参数
    public String saveMd(@RequestBody JSONObject param){
    //取出java中对应参数的值
    String str = param.getString("content");
    String name=param.getString("name");
    String typeId=param.getString("typeId");
    //文件保存路径  F:\note\555.md
    String filepath=abpath+name+".md";
    FileUtil.string2File(str,filepath);
    return "ok";
}

    //上传图片
    @PostMapping("/uploadFile")
    public String uploadFile(@RequestParam("image") MultipartFile file, HttpServletRequest request){
        //上传的绝对路径  F:/note/assets/
        String imgAbPath=abpath+"assets/";
        //绝对路径对应urlpath   http://localhost:4000/note/assets/
//        String imgUrlDir="http:"+request.getHeader("Origin").split(":")[1]+":"+port+mdImageDir;
        String imgUrlDir = "http://120.79.128.109:7070/img/assets/";
        //返回对应的File类型f
        File f = FileUtil.upload(file, imgAbPath);

        //返回图片地址 http://localhost:4000/note/assets/image-20200924014614792.png  注意图片名子中间有加密
        return imgUrlDir+f.getName();

    }

}
